# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.viewset import CustomModelViewSet
from core.response import JsonResponse
from apps.pms.models import Module
from apps.pms.module.serializers import *
from apps.pms.module.resources import *
from apps.pms.module.filters import *
from utils.tree import list2tree


class ModuleViewSet(CustomModelViewSet):
    """
    模块管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Module.objects.all()
    serializer_class = ModuleSerializer
    list_serializer_class = ListModuleSerializer
    filterset_class = ModuleFilterSet
    import_resources = ModuleResouces
    export_resources = ModuleResouces

    @action(detail=False, methods=["GET"])
    def prefix(self, request, *args, **kwargs):
        module = Module.objects.get(id=request.query_params["id"])
        prefix_list = [module.product.number]
        prefix_list.append(module.number)
        data = "_".join(prefix_list)
        return JsonResponse(data=data, msg="获取成功")

    @action(detail=False, methods=["GET"])
    def treeselect(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = ModuleTreeSelectSerializer(queryset, many=True, request=request)
        data = list2tree(serializer.data)
        return JsonResponse(data=data, msg="获取成功")
